<template>
  <div class="violent-motorcycle-container">
    <!-- 游戏主画布 -->
    <canvas ref="gameCanvas" class="game-canvas"></canvas>

    <!-- 游戏状态面板 -->
    <div class="game-status">
      <div class="status-item">
        <span class="status-label">分数</span>
        <span class="status-value">{{ score }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">距离</span>
        <span class="status-value">{{ distance }}m</span>
      </div>
      <div class="status-item">
        <span class="status-label">时间</span>
        <span class="status-value">{{ formatTime(time) }}</span>
      </div>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel" v-if="!gameStarted">
      <h2>暴力摩托</h2>
      <div class="bike-selection">
        <h3>选择摩托车</h3>
        <div class="bike-options">
          <div v-for="bike in bikes" 
               :key="bike.id" 
               class="bike-option"
               :class="{ active: selectedBike === bike.id }"
               @click="selectBike(bike.id)">
            <img :src="bike.image" :alt="bike.name">
            <div class="bike-info">
              <h4>{{ bike.name }}</h4>
              <div class="bike-stats">
                <div class="stat">
                  <span class="stat-label">速度</span>
                  <div class="stat-bar">
                    <div class="stat-fill" :style="{ width: bike.speed + '%' }"></div>
                  </div>
                </div>
                <div class="stat">
                  <span class="stat-label">操控</span>
                  <div class="stat-bar">
                    <div class="stat-fill" :style="{ width: bike.handling + '%' }"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <button class="start-button" @click="startGame">开始游戏</button>
    </div>

    <!-- 游戏结束面板 -->
    <div class="game-over" v-if="gameOver">
      <div class="game-over-content">
        <h2>游戏结束</h2>
        <div class="final-score">
          <div class="score-item">
            <span class="score-label">总分</span>
            <span class="score-value">{{ score }}</span>
          </div>
          <div class="score-item">
            <span class="score-label">距离</span>
            <span class="score-value">{{ distance }}m</span>
          </div>
          <div class="score-item">
            <span class="score-label">时间</span>
            <span class="score-value">{{ formatTime(time) }}</span>
          </div>
        </div>
        <div class="action-buttons">
          <button @click="restartGame">重新开始</button>
          <button @click="returnToMenu">返回菜单</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

// 游戏状态
const gameCanvas = ref(null)
const ctx = ref(null)
const gameStarted = ref(false)
const gameOver = ref(false)
const score = ref(0)
const distance = ref(0)
const time = ref(0)
const selectedBike = ref('bike1')

// 游戏物理参数
const player = ref({
  x: 0,
  y: 0,
  speed: 0,
  acceleration: 0,
  rotation: 0,
  isJumping: false
})

// 游戏场景
const track = ref({
  segments: [],
  obstacles: []
})

// 生成赛道
const generateTrack = () => {
  const segments = []
  const obstacles = []
  
  // 生成赛道段落
  for (let i = 0; i < 100; i++) {
    segments.push({
      x: i * 200,
      y: Math.sin(i * 0.1) * 50, // 赛道起伏
      width: 200,
      height: 20
    })
    
    // 随机生成障碍物
    if (Math.random() < 0.3) {
      obstacles.push({
        x: i * 200 + Math.random() * 150,
        y: Math.sin(i * 0.1) * 50 - 30,
        width: 20,
        height: 20,
        type: Math.random() < 0.5 ? 'rock' : 'barrier'
      })
    }
  }
  
  track.value.segments = segments
  track.value.obstacles = obstacles
}

// 路由
const router = useRouter()

// 摩托车选项
const bikes = [
  {
    id: 'bike1',
    name: '街头战士',
    image: '/img/bikes/street-fighter.png',
    speed: 80,
    handling: 70
  },
  {
    id: 'bike2',
    name: '竞速战神',
    image: '/img/bikes/speed-demon.png',
    speed: 90,
    handling: 60
  },
  {
    id: 'bike3',
    name: '越野之王',
    image: '/img/bikes/off-road-king.png',
    speed: 70,
    handling: 85
  }
]

// 游戏循环
let gameLoop
let lastTime = 0

// 选择摩托车
const selectBike = (bikeId) => {
  selectedBike.value = bikeId
}

// 开始游戏
const startGame = () => {
  gameStarted.value = true
  gameOver.value = false
  score.value = 0
  distance.value = 0
  time.value = 0
  initGame()
}

// 重启游戏
const restartGame = () => {
  gameOver.value = false
  score.value = 0
  distance.value = 0
  time.value = 0
  startGame()
}

// 返回菜单
const returnToMenu = () => {
  gameStarted.value = false
  gameOver.value = false
}

// 格式化时间
const formatTime = (timeInSeconds) => {
  const minutes = Math.floor(timeInSeconds / 60)
  const seconds = timeInSeconds % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 初始化游戏
const initGame = () => {
  const canvas = gameCanvas.value
  ctx.value = canvas.getContext('2d')

  // 设置画布尺寸
  const resizeCanvas = () => {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
  }

  resizeCanvas()
  window.addEventListener('resize', resizeCanvas)

  // 开始游戏循环
  lastTime = performance.now()
  gameLoop = requestAnimationFrame(update)
}

// 游戏更新循环
const update = (currentTime) => {
  const deltaTime = (currentTime - lastTime) / 1000
  lastTime = currentTime

  // 更新游戏状态
  if (gameStarted.value && !gameOver.value) {
    time.value += deltaTime
    
    // 更新玩家位置和速度
    const selectedBikeData = bikes.find(b => b.id === selectedBike.value)
    const maxSpeed = selectedBikeData.speed * 0.5
    const handling = selectedBikeData.handling * 0.1
    
    // 加速度控制
    if (controls.value.up) {
      player.value.speed = Math.min(player.value.speed + maxSpeed * 0.1 * deltaTime, maxSpeed)
    } else if (controls.value.down) {
      player.value.speed = Math.max(player.value.speed - maxSpeed * 0.2 * deltaTime, 0)
    }
    
    // 转向控制
    if (controls.value.left) {
      player.value.rotation -= handling * deltaTime
    }
    if (controls.value.right) {
      player.value.rotation += handling * deltaTime
    }
    
    // 更新位置
    player.value.x += Math.cos(player.value.rotation) * player.value.speed * deltaTime
    player.value.y += Math.sin(player.value.rotation) * player.value.speed * deltaTime
    
    // 更新距离和分数
    distance.value = Math.floor(Math.sqrt(player.value.x * player.value.x + player.value.y * player.value.y))
    score.value = Math.floor(distance.value * (player.value.speed / maxSpeed))
    
    // 重力效果
    if (player.value.isJumping) {
      player.value.y += 9.8 * deltaTime * 50 // 简单的重力效果
      if (player.value.y >= 0) { // 假设 0 是地面
        player.value.y = 0
        player.value.isJumping = false
      }
    }
  }

  // 渲染游戏画面
  render()

  // 继续游戏循环
  if (!gameOver.value) {
    gameLoop = requestAnimationFrame(update)
  }
}

// 渲染游戏画面
const render = () => {
  const canvas = gameCanvas.value
  const context = ctx.value

  // 清空画布
  context.clearRect(0, 0, canvas.width, canvas.height)

  // 保存当前状态
  context.save()

  // 移动画布原点到中心
  context.translate(canvas.width / 2, canvas.height / 2)

  // 相机跟随玩家
  context.translate(-player.value.x, -player.value.y)

  // 绘制背景
  const gradient = context.createLinearGradient(0, -canvas.height, 0, canvas.height)
  gradient.addColorStop(0, '#87CEEB') // 天空色
  gradient.addColorStop(1, '#8B4513') // 地面色
  context.fillStyle = gradient
  context.fillRect(player.value.x - canvas.width, -canvas.height, canvas.width * 2, canvas.height * 2)

  // 绘制赛道
  context.beginPath()
  track.value.segments.forEach((segment, index) => {
    if (index === 0) {
      context.moveTo(segment.x, segment.y)
    } else {
      context.lineTo(segment.x, segment.y)
    }
  })
  context.strokeStyle = '#333'
  context.lineWidth = 20
  context.stroke()

  // 绘制障碍物
  track.value.obstacles.forEach(obstacle => {
    context.fillStyle = obstacle.type === 'rock' ? '#666' : '#f00'
    context.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height)
  })

  // 绘制摩托车
  context.save()
  context.translate(player.value.x, player.value.y)
  context.rotate(player.value.rotation)

  // 摩托车车身
  context.fillStyle = '#000000'
  context.fillRect(-20, -10, 40, 20)

  // 车轮
  context.beginPath()
  context.arc(-15, 10, 8, 0, Math.PI * 2)
  context.arc(15, 10, 8, 0, Math.PI * 2)
  context.fill()

  // 悬挂系统
  context.strokeStyle = '#666'
  context.lineWidth = 3
  context.beginPath()
  context.moveTo(-15, 0)
  context.lineTo(-15, 10)
  context.moveTo(15, 0)
  context.lineTo(15, 10)
  context.stroke()

  context.restore()

  // 恢复画布状态
  context.restore()
}

// 组件挂载时初始化
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)
  if (gameLoop) {
    cancelAnimationFrame(gameLoop)
  }
})

// 键盘事件处理
const handleKeyDown = (event) => {
  // TODO: 处理键盘按下事件
}

const handleKeyUp = (event) => {
  // TODO: 处理键盘松开事件
}
</script>

<style scoped>
.violent-motorcycle-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.game-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.game-status {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 2;
  display: flex;
  gap: 20px;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px 20px;
  border-radius: 10px;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-label {
  color: #ffffff;
  font-size: 14px;
  opacity: 0.8;
}

.status-value {
  color: #ffffff;
  font-size: 24px;
  font-weight: bold;
}

.control-panel {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
  background: rgba(0, 0, 0, 0.8);
  padding: 30px;
  border-radius: 15px;
  color: #ffffff;
  text-align: center;
}

.bike-selection {
  margin: 20px 0;
}

.bike-options {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.bike-option {
  background: rgba(255, 255, 255, 0.1);
  padding: 15px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.bike-option:hover {
  background: rgba(255, 255, 255, 0.2);
}

.bike-option.active {
  background: rgba(255, 255, 255, 0.3);
  border: 2px solid #4CAF50;
}

.bike-info {
  margin-top: 10px;
}

.bike-stats {
  margin-top: 10px;
}

.stat {
  margin: 5px 0;
}

.stat-bar {
  width: 100%;
  height: 5px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
  overflow: hidden;
}

.stat-fill {
  height: 100%;
  background: #4CAF50;
  transition: width 0.3s ease;
}

.start-button {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.start-button:hover {
  background: #45a049;
  transform: scale(1.05);
}

.game-over {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3;
}

.game-over-content {
  background: rgba(255, 255, 255, 0.1);
  padding: 30px;
  border-radius: 15px;
  text-align: center;
  color: #ffffff;
}

.final-score {
  margin: 20px 0;
  display: flex;
  gap: 20px;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.action-buttons button {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-buttons button:hover {
  background: #45a049;
  transform: scale(1.05);
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .control-panel {
    background: rgba(30, 41, 59, 0.8);
  }

  .bike-option {
    background: rgba(30, 41, 59, 0.5);
  }

  .bike-option:hover {
    background: rgba(30, 41, 59, 0.7);
  }

  .bike-option.active {
    background: rgba(30, 41, 59, 0.9);
    border-color: #3b82f6;
  }

  .stat-fill {
    background: #3b82f6;
  }

  .start-button,
  .action-buttons button {
    background: #3b82f6;
  }

  .start-button:hover,
  .action-buttons button:hover {
    background: #2563eb;
  }
}
</style>